import {
  reqOrderAddress,
  reqOrderInfo,
  reqBuyNowGoods,
  reqSubmitOrder,
  reqPrePayInfo,
  reqPayStatus
} from "../../../api/orderPay"
import {
  formatTime
} from "../../../utils/formatTime"
//导入async-validator进行表单验证
import Schema from "async-validator"
import {
  debounce
} from "miniprogram-licia"
const app = getApp()
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    orderAddress: {}, //收获地址
    orderInfo: {}, //订单商品详情
  },

  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    //使用Vant提供的时间选择组件，获取的是时间戳
    //可以调用小程序提供的日期格式化方法
    const timeRes = formatTime(new Date(event.detail))
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  },
  //获取订单支付页面的收获地址
  async getAddress() {
    //判断全局共享的address中是否存在数据
    //如果存在数据，就从全局共享address中获取数据
    const addressId = app.globalData.address.id
    if (addressId) {
      this.setData({
        orderAddress: app.globalData.address
      })
      return
    }

    const {
      data: orderAddress
    } = await reqOrderAddress()
    this.setData({
      orderAddress
    })

  },
  //获取订单详情数据
  async getOrderInfo() {
    const {
      goodsId,
      blessing
    } = this.data
    const {
      data: orderInfo
    } = goodsId ? await reqBuyNowGoods({
      goodsId,
      blessing
    }) : await reqOrderInfo()
    // //判断是否存在祝福语
    const orderGoods = orderInfo.cartVoList.find((item) => item.blessing !== "")
    this.setData({
      orderInfo,
      blessing: !orderGoods ? "" : orderGoods.blessing
    })
  },
  //对订购人信息进行参数进行验证
  validatorPerson(params) {
    //验证订购人，是否包含大小写字母，数字和中文字符
    const nameRegExp = "^[a-zA-Z\\d\\u4e00-\\u9fa5]+$"
    //验证手机号，是否符合大陆手机号格式
    const phoneRegExp = "^1(?:3\\d|4[4-9]5[0-35-9]6[67]7[0-8]|8\\d|9\\d)\\d{8}$"

    //创建验证规则
    const rules = {
      userAddressId: {
        required: true,
        message: "请选择收货地址"
      },
      buyName: [{
          required: true,
          message: "请输入订购人姓名"
        },
        {
          pattern: nameRegExp,
          message: "订购人姓名不合法"
        }
      ],
      buyPhone: [{
          required: true,
          message: "请输入订购人手机号"
        },
        {
          pattern: phoneRegExp,
          message: "订购人手机号不合法"
        }
      ],
      deliveryDate: {
        required: true,
        message: "请选择送达日期"
      }
    }
    //传入验证规则进行实例化
    const validator = new Schema(rules)

    //调用实例方法对请求参数进行验证
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          //如果验证失败，需要提示用户
          wx.toast({
            title: errors[0].message
          })
          resolve({
            valid: false
          })
        } else {
          resolve({
            valid: true
          })
        }
      })
    })
  },
  //提交订单
  submitOrder: debounce(async function () {
    //需要从data中解构数据，根据接口要求，组织请求参数以后对请求参数进行验证
    const {
      buyName,
      buyPhone,
      deliveryDate,
      blessing,
      orderAddress,
      orderInfo
    } = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const {
      valid
    } = await this.validatorPerson(params)
    if (!valid) return
    const res = await reqSubmitOrder(params)
    if (res.code === 200) {
      //平台订单创建成功以后，需要将服务器返回的订单编号挂载到页面实例上
      this.orderNo = res.data
      //获取预支付订单信息、支付参数
      this.advancePay()
    }
  }, 500),
  async advancePay() {
    try {
      const payParams = await reqPrePayInfo(this.orderNo)
      if (payParams.code === 200) {
        //payParams.data 就是获取的支付参数
        const payInfo = await wx.requestPayment(payParams.data)
        //获取支付的结果
        if (payInfo.errMsg === "requestPayment:ok") {
          //查询支付状态
          const payStatus = await reqPayStatus(this.orderNo)
          if (payStatus.code == 200) {
            wx.redirectTo({
              url: "/modules/orderPayModule/pages/order/list/list",
              success: () => {
                wx.toast({
                  title: "支付成功",
                  icon: "success"
                })
              }
            })
          }
        }
      }
    } catch (error) {
      wx.toast({
        title: "支付失败",
        icon: "error"
      })
    }
  },
  //页面加载时触发
  onLoad(options) {
    //获取立即购买商品传递的参数
    this.setData({
      ...options
    })
  },
  //页面展示时进行触发
  onShow() {
    this.getAddress()
    this.getOrderInfo()
  },
  onUnload() {
    //页面销毁以后，将全局共享的address进行销毁
    app.globalData.address = {}
  }
})